package cn.fastoo.common.utils;

import com.google.i18n.phonenumbers.NumberParseException;
import com.google.i18n.phonenumbers.PhoneNumberUtil;
import com.google.i18n.phonenumbers.Phonenumber;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class PhoneNumberUtils {

    private final static Logger log = LoggerFactory.getLogger(PhoneNumberUtils.class);

    public static boolean isValidNumber(String numberStr){
        String numberS = numberStr;
        if(!numberS.startsWith("+")){
            numberS = "+" + numberS;
        }

        PhoneNumberUtil phoneUtil = PhoneNumberUtil.getInstance();
        try {
            Phonenumber.PhoneNumber number = phoneUtil.parseAndKeepRawInput(numberS, "");

            boolean isPossibleNumber = phoneUtil.isPossibleNumber(number);
            if(!isPossibleNumber) return false;

            return phoneUtil.isValidNumber(number);
        } catch (NumberParseException e){
            log.error("解析号码异常:" + numberStr);
            return false;
        }
    }

    public static String getCountryCode(String numberStr){
        String numberS = numberStr;
        if(!numberS.startsWith("+")){
            numberS = "+" + numberS;
        }

        PhoneNumberUtil phoneUtil = PhoneNumberUtil.getInstance();
        try {
            Phonenumber.PhoneNumber number = phoneUtil.parseAndKeepRawInput(numberS, "");
            return phoneUtil.getRegionCodeForNumber(number);
        } catch (NumberParseException e) {
            log.error("解析号码异常:" + numberStr);
            return "";
        }
    }


    public static void main(String []args){
        String dest = "08615160097516";
        dest = dest.replaceFirst("^0+(?!$)", "");

        //System.out.println(dest);

//        System.out.println(isValidNumber("868615160097516"));
 //       System.out.println(isValidNumber("97699920049"));
        System.out.println(isValidNumber("61407113832"));
        //System.out.println(getCountryCode("60174183310"));
    }
}
